<script language="javascript">


function print_today() {
  // ***********************************************
  // AUTHOR: WWW.CGISCRIPT.NET, LLC
  // URL: http://www.cgiscript.net
  // Use the script, just leave this message intact.
  // Download your FREE CGI/Perl Scripts today!
  // ( http://www.cgiscript.net/scripts.htm )
  // ***********************************************
  var now = new Date();
  var months = new Array('Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre');
  var date = ((now.getDate()<10) ? "0" : "")+ now.getDate();
  function fourdigits(number) {
    return (number < 1000) ? number + 1900 : number;
  }
  var today =  months[now.getMonth()] + " " + date + ", " + (fourdigits(now.getYear()));
  return today;
}

function formato_numero(numero, decimales, separador_decimal, separador_miles){ // v2007-08-06 
    numero=parseFloat(numero);
    if(isNaN(numero)){
        return "";
    }

    if(decimales!==undefined){
        // Redondeamos
        numero=numero.toFixed(decimales);
    }

    // Convertimos el punto en separador_decimal
    numero=numero.toString().replace(".", separador_decimal!==undefined ? separador_decimal : ",");

    if(separador_miles){
        // Añadimos los separadores de miles
        var miles=new RegExp("(-?[0-9]+)([0-9]{3})");
        while(miles.test(numero)) {
            numero=numero.replace(miles, "$1" + separador_miles + "$2");
        }
    }

    return numero;
}

// from http://www.mediacollege.com/internet/javascript/number/round.html
function roundNumber(number,decimals) {
  var newString;// The new rounded number
  decimals = Number(decimals);
  if (decimals < 1) {
    newString = (Math.round(number)).toString();
  } else {
    var numString = number.toString();
    if (numString.lastIndexOf(".") == -1) {// If there is no decimal point
      numString += ".";// give it one at the end
    }
    var cutoff = numString.lastIndexOf(".") + decimals;// The point at which to truncate the number
    var d1 = Number(numString.substring(cutoff,cutoff+1));// The value of the last decimal place that we'll end up with
    var d2 = Number(numString.substring(cutoff+1,cutoff+2));// The next decimal, after the last one we want
    if (d2 >= 5) {// Do we need to round up at all? If not, the string will just be truncated
      if (d1 == 9 && cutoff > 0) {// If the last digit is 9, find a new cutoff point
        while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {
          if (d1 != ".") {
            cutoff -= 1;
            d1 = Number(numString.substring(cutoff,cutoff+1));
          } else {
            cutoff -= 1;
          }
        }
      }
      d1 += 1;
    } 
    if (d1 == 10) {
      numString = numString.substring(0, numString.lastIndexOf("."));
      var roundedNum = Number(numString) + 1;
      newString = roundedNum.toString() + '.';
    } else {
      newString = numString.substring(0,cutoff) + d1.toString();
    }
  }
  if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string
    newString += ".";
  }
  var decs = (newString.substring(newString.lastIndexOf(".")+1)).length;
  for(var i=0;i<decimals-decs;i++) newString += "0";
  //var newNumber = Number(newString);// make it a number if you like
  return newString; // Output the result to the form field (change for your purposes)
}

function update_total() {
  var total = 0;
  $('.price').each(function(i){
    price = $(this).html().replace("$","");
    if (!isNaN(price)) total += Number(price);
  });
 // total = roundNumber(total,2);



  var iva = total*0.16;
$('#iva').html("$"+iva);


 document.formulario.ivatotal.value = formato_numero(iva,2,',','.');
  


  var totales = Number(iva)+Number(total);


 // $('#ivaporcentaje').html("$"+ivaporcentaje);
  $('#subtotal').html("$"+total);
  
   document.formulario.subtotal.value = formato_numero(total,0,',','.');

 $('#deuda_total').html("$"+totales);
   $('#total').html("$"+totales);
   

  
 // $('input .deuda_total').html("$"+total);
 // $('input .sub_total').html("$"+subtotal);
//  $('input .iva_tola').html("$"+iva);
	
   


  

  
  
  update_balance();

}



function update_balance() {
//  var due = $("#total").html().replace("$","") - $("#paid").val().replace("$","");
  //due = roundNumber(due,0);
//document.formulario.iva_porcentaje.value = ivaporcentaje;
//document.formulario.sub_total.value = subtotal;
//document.formulario.deuda_total.value = due;
	
 // $('.due').html("$"+due);
 
 
   var due = Number($("#total").html().replace("$","")) - Number($("#paid").val().replace("$",""));

  $('.due').html("$"+due);
  document.formulario.deuda_total.value = formato_numero(due,0,',','.');
  
}

function update_price() {
	


	
	
  var row = $(this).parents('.item-row'); 

var resta_v = (row.find('.stock').val() - row.find('.qty').val());
 
   if(resta_v >= 0 )
   {
	   
  var price = row.find('.cost').val().replace("$","") * row.find('.qty').val();
  
// var precios = formato_numero(row.find('.cost').val().replace("$","") * row.find('.qty').val(),0,',','.');

	  
	  update_balance();
   //document.formulario.precio.value = price;
 
  }else{
	  alert('no hay suficiente inventario');

	 

  }

	    isNaN(price) ? row.find('.price').html("N/A") : row.find('.price').html("$"+price);

 // price = roundNumber(price,2);
//  isNaN(price) ? row.find('.price').html("N/A") : row.find('.price').html("$"+price);
  


  
  update_total();
}

function bind() {

$(".stock").blur(update_price);
  $(".cost").blur(update_price);
//  $(".qty").keyup(update_price);
  $(".qty").blur(update_price);
}

$(document).ready(function() {

  $('input').click(function(){
    $(this).select();
  });


  
  $("#paid").blur(update_balance);
   
  $("#addrow").click(function(){

    $(".item-row:last").after('  <tr class="item-row" align="center">    <td <?php echo $color_tabla1;  ?>>'+
               
 '<div class="delete-wpr"><a class="delete" href="javascript:;" title="Remove row">X</a></div><input type="hidden" name="codigo_producto[]" id="codigo"  value="<?php echo $resultado_envio["codigo"]; ?>"  >'+
 
 ' <div data-role="fieldcontain">  <input type="text" name="descripcion[]" id="descripcion<?php echo $i; ?>"  value="<?php echo $resultado_envio["descripcion"]; ?>"   ></div>'+
             
'</td> <td <?php echo $color_tabla1; ?> >  <div data-role="fieldcontain">  <input type="text" id="stock"  name="stock[]" class="stock" > </div></td>  ' +
                         
 '<td  <?php echo $color_tabla1; ?>>  <div data-role="fieldcontain"  > <input type="text"  id="cost" name="cost[]" class="cost" value="<?php echo $resultado_envio["precios"]; ?>"></div></td>'+
  
'<td <?php echo $color_tabla1;  ?>>  <div data-role="fieldcontain" > <input type="text" name="qty[]" class="qty"> </div></td>'+
              
' <td  <?php echo $color_tabla2; ?> align="center"> <span class="price" > </span></td> </tr>');
    if ($(".delete").length > 0) $(".delete").show();
    bind();
  });
  
  bind();
  
  $(".delete").live('click',function(){
    $(this).parents('.item-row').remove();
    update_total();
    if ($(".delete").length < 2) $(".delete").hide();
  });
  
  $("#cancel-logo").click(function(){
    $("#logo").removeClass('edit');
  });
  $("#delete-logo").click(function(){
    $("#logo").remove();
  });
  $("#change-logo").click(function(){
    $("#logo").addClass('edit');
    $("#imageloc").val($("#image").attr('src'));
    $("#image").select();
  });
  $("#save-logo").click(function(){
    $("#image").attr('src',$("#imageloc").val());
    $("#logo").removeClass('edit');
  });
  
  $("#date").val(print_today());
  
});

</script>